<template>
  <pageHeader :title="title" :breadCrumb="breadCrumb" :show-back="true">
    <template #buts>
      <a-button type="primary" @click="addBuyApply">
        <template #icon>
          <icon-plus></icon-plus>
        </template>
        <template #default>新建采购申请</template>
      </a-button>
    </template>
  </pageHeader>
  <div>
    <a-tabs @change="searchState" type="line">
      <a-tab-pane :key="0" title="全部申请"> </a-tab-pane>
      <a-tab-pane :key="1" title="我的申请"> </a-tab-pane>
    </a-tabs>
  </div>
  <div class="search-box">
    <div>
      <a-space>
        <a-input-group>
          <!-- <a-select
            :style="{ width: '120px' }"
            placeholder="请选择"
            v-model="currSelectVal"
            :default-value="currSelectVal"
          >
            <a-option value="number"></a-option>
          </a-select> -->
          <a-input-search
            search-button
            :style="{ width: 'auto' }"
            placeholder="请输入采购申请单号"
            v-model="currSelectSearch"
            @search="search"
          />
        </a-input-group>

        <a-select placeholder="请选择" v-model="userState" @change="search">
          <template #prefix>状态：</template>
          <a-option :value="1">待执行</a-option>
          <a-option :value="4">执行中</a-option>
          <a-option :value="3">审核中</a-option>
          <a-option :value="6">已完成</a-option>
          <a-option :value="5">不通过</a-option>
          <a-option :value="7">异常完成</a-option>
          <a-option :value="0">全部</a-option>
        </a-select>
        <a-select v-model="priorityData" placeholder="请选择" @change="search">
          <template #prefix>优先级：</template>
          <a-option :value="1">低</a-option>
          <a-option :value="2">中</a-option>
          <a-option :value="3">高</a-option>
          <a-option :value="4">紧急</a-option>
          <a-option :value="0">全部</a-option>
        </a-select>
        <a-button type="outline" @click="reset">
          <template #icon>
            <icon-refresh />
          </template>
          <template #default>重置</template>
        </a-button>
      </a-space>
    </div>
    <div>
      <a-space>
        <a-button status="success">
          <template #icon>
            <icon-download />
          </template>
          <template #default>导入</template>
        </a-button>

        <a-button status="warning">
          <template #icon>
            <icon-export rotate="-90" />
          </template>
          <template #default>导出</template>
        </a-button>

        <a-button type="primary" @click="showFormHeaderSetting"
          >表头设置</a-button
        >
      </a-space>
    </div>
  </div>
  <div style="padding: 10px">
    <tableTurn :tableData="getData" :args="args" ref="tableRef">
      <a-table-column :width="80" align="center">
        <template #title> 序号 </template>
        <template #cell="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
      </a-table-column>
      <a-table-column
        v-for="item in selectedHeader"
        :key="item.code"
        :title="item.name"
        :data-index="item.code"
        :width="150"
        align="center"
        :ellipsis="true"
        :tooltip="{
          position: 'top',
        }"
      >
        <template v-if="item.code === 'applyDetail'" #cell="{ record }">
          <a-tooltip content="查看">
            <IconFont
              type="icon-chakan1"
              :size="30"
              :style="{
                marginRight: '10px',
                cursor: 'pointer',
              }"
              @click="See(record.product)"
            />
          </a-tooltip>
        </template>

        <template v-else-if="item.code === 'cause'" #cell="{ record }">
          <a-tooltip content="查看">
            <IconFont
              type="icon-chakan1"
              :size="30"
              :style="{
                marginRight: '10px',
                cursor: 'pointer',
              }"
              @click="view(record.description)"
            />
          </a-tooltip>
        </template>

        <template v-else-if="item.code === 'applyTime'" #cell="{ record }">
          {{ dayjs(record.applyTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>

        <template v-else-if="item.code === 'createdAt'" #cell="{ record }">
          {{ dayjs(record.createdAt).format('YYYY-MM-DD') }}
        </template>

        <template v-else-if="item.code === 'priority'" #cell="{ record }">
          <a-typography-text
            v-if="record.priority === 1"
            style="color: #999999"
          >
            低
          </a-typography-text>
          <a-typography-text v-if="record.priority === 2" type="primary">
            中
          </a-typography-text>
          <a-typography-text v-if="record.priority === 3" type="warning">
            高
          </a-typography-text>
          <a-typography-text v-if="record.priority === 4" type="danger">
            紧急
          </a-typography-text>
        </template>

        <template v-else-if="item.code === 'okState'" #cell="{ record }">
          <a-typography-text
            v-if="record.state === 2 || record.state === 1"
            style="color: #999999"
          >
            待审核
          </a-typography-text>
          <a-typography-text v-if="record.state === 3" type="primary">
            审核中
          </a-typography-text>
          <a-typography-text
            v-if="
              record.state === 4 || record.state === 6 || record.state === 7
            "
            type="success"
          >
            已通过
          </a-typography-text>
          <a-typography-text v-if="record.state === 5" type="danger">
            不通过
          </a-typography-text>
        </template>

        <template v-else-if="item.code === 'state'" #cell="{ record }">
          <div
            class="status"
            :style="{
              color: orderStatus.filter((ele) => ele.id === record.state)[0]
                ?.backgroundColor,
            }"
          >
            <p
              :style="{
                'background': orderStatus.filter(
                  (ele) => ele.id === record.state
                )[0]?.backgroundColor,
                'box-shadow': `0px 0px 5px`,
              }"
            ></p>
            {{ orderStatus.filter((ele) => ele.id === record.state)[0]?.value }}
          </div>
        </template>
      </a-table-column>
      <a-table-column :width="150" fixed="right" title="操作" align="center">
        <template #title> 操作 </template>
        <template #cell="{ record }">
          <div v-if="saveUserId.id === record.createBy">
            <a-space v-if="record.state === 1">
              <!-- <a-button type="primary" status="success" 
                >提交审核</a-button
              > -->
              <a-tooltip content="提交审核">
                <IconFont
                  type="icon-tijiaoshenhe1"
                  :size="26"
                  :style="{
                    marginRight: '10px',
                    cursor: 'pointer',
                  }"
                  @click="Submit(record)"
                />
              </a-tooltip>

              <a-tooltip content="进入详情">
                <IconFont
                  type="icon-details-def"
                  :size="26"
                  :style="{
                    marginRight: '10px',
                    cursor: 'pointer',
                  }"
                  @click="edit(record.id)"
                />
              </a-tooltip>
              <a-tooltip content="删除">
                <a-popconfirm
                  content="确认删除？"
                  type="error"
                  @ok="del(record.id)"
                >
                  <IconFont
                    type="icon-delete"
                    :size="26"
                    :style="{
                      marginRight: '10px',
                      cursor: 'pointer',
                    }"
                  />
                </a-popconfirm>
              </a-tooltip>
            </a-space>
            <a-space v-else>
              <a-tooltip content="进入详情">
                <IconFont
                  type="icon-details-def"
                  :size="26"
                  :style="{
                    marginRight: '10px',
                    cursor: 'pointer',
                  }"
                  @click="edit(record.id)"
                />
              </a-tooltip>
            </a-space>
          </div>
          <!-- <div v-else @click="edit(record.id)">
            <a-button type="text">申请详情</a-button>
          </div> -->
        </template>
      </a-table-column>
    </tableTurn>
  </div>
  <FormHeaderSetting
    v-model:visible="formHeaderSettingVisible"
    title="采购申请列表表头设置"
    :resultList="headerSetting.list"
    @headerSave="headerSave"
  ></FormHeaderSetting>
  <ViewDetails v-model:visible="modelVisible" :SeeDate="SeeDate"> </ViewDetails>
  <ViewCause
    v-model:visible="modelCauseVisible"
    :SeeCauseDate="SeeCauseDate"
  ></ViewCause>
</template>

<script lang="ts" setup>
  import { reactive, ref, computed, onMounted } from 'vue';
  import { useRouter } from 'vue-router';
  import dayjs from 'dayjs';
  import {
    getPurchaseHeader,
    PUTPurchaseHeader,
    getPurchaseApplyList,
    delPurchaseApplyList,
    PutPurchaseApplyList,
  } from '@/api/buy-management/buy-apply/index';
  import ViewDetails from './view-details/index.vue';
  import ViewCause from './view-cause/index.vue';

  const router = useRouter();
  const title: string = '采购申请列表';
  const breadCrumb: string[] = ['采购管理', '采购管理', '采购申请列表'];
  const modelVisible = ref(false);
  const formHeaderSettingVisible = ref(false);
  let tableRef: any = ref(); // 储存table的ref
  let currSelectVal = ref(); // 储存当前下拉选择框的值
  let currSelectSearch = ref(''); // 储存下拉选择框对应的搜索框的值
  const modelCauseVisible = ref(false);
  const userState = ref();
  const TimeData = ref();
  const beginTime = ref();
  const endTime = ref();
  const ownList = ref();
  const saveUserId = ref<any>(
    JSON.parse(sessionStorage.getItem('loginInfo') as any)
  );

  // const arr1 = ['aa', 'bb', NaN];
  // const arr2 = ['bb', 'aa', NaN];

  // const getArr = () => {
  //   if (arr1.length !== arr2.length) {
  //     return false;
  //   }
  //   arr1.forEach((ele) => {
  //     console.log(arr2.indexOf(ele));
  //   });
  //   // console.log(arr1.toString());
  // };
  // getArr();
  const orderStatus = [
    { id: 1, value: '待提交', backgroundColor: '#cccccc' },
    { id: 2, value: '待提交', backgroundColor: '#009933' },
    { id: 3, value: '审核中', backgroundColor: '#4e8bfb' },
    { id: 4, value: '执行中', backgroundColor: '#4e8bfb' },
    { id: 5, value: '不通过', backgroundColor: '#DC143C' },
    { id: 6, value: '已完成', backgroundColor: '#009933' },
  ];

  // 储存表头数据
  const priorityData = ref(); // 储存搜索优先级的值
  const headerSetting = reactive<any>({
    list: [],
  });

  const getData = async (page: any) => {
    try {
      const msg: any = {};
      if (currSelectSearch.value) msg.number = currSelectSearch.value;
      if (userState.value) msg.state = userState.value;
      if (priorityData.value) msg.priority = priorityData.value;
      if (ownList.value) msg.ownList = ownList.value;
      if (beginTime.value) msg.beginTime = beginTime.value;
      if (endTime.value) msg.endTime = endTime.value;

      let res = await getPurchaseApplyList({
        ...page,
        ...msg,
      });

      if (res.content === null || res.content === undefined) {
        res.content = [];
      }

      res.content.map((item: any) => {
        item.show = false;
        return item;
      });

      return Promise.resolve(res);
    } catch (err: unknown) {
      console.log(err);
    }
  };

  const columns = [
    {
      code: 'name',
      isDefault: 1,
      name: '采购申请名称',
    },
    {
      code: 'number',
      isDefault: 1,
      name: '采购申请单号',
    },
    {
      code: 'priority',
      isDefault: 1,
      name: '优先级',
    },
    {
      code: 'applyDetail',
      isDefault: 1,
      name: '申请明细',
    },
    {
      code: 'cause',
      isDefault: 1,
      name: '申请原因',
    },
    {
      code: 'createByName',
      isDefault: 1,
      name: '申请人',
    },
    {
      code: 'applyTime',
      isDefault: 1,
      name: '申请日期',
    },
    {
      code: 'okState',
      isDefault: 1,
      name: '审核状态',
    },
    {
      code: 'state',
      isDefault: 1,
      name: '执行状态',
    },
    {
      code: 'createdAt',
      isDefault: 1,
      name: '创建时间',
    },
    {
      code: 'deptName',
      isDefault: 2,
      name: '申请部门',
    },
  ];

  const showFormHeaderSetting = () => {
    formHeaderSettingVisible.value = true;
  };

  const headerSettingData = async () => {
    try {
      const res = await getPurchaseHeader({
        userId: saveUserId.value.id,
        listType: 1,
      });
      headerSetting.list = res.extends ? res.extends : columns;
    } catch (err: unknown) {
      console.log(err);
    }
  };
  headerSettingData();

  const reset = () => {
    currSelectVal.value = '';
    currSelectSearch.value = '';
    userState.value = undefined;
    priorityData.value = undefined;
    beginTime.value = undefined;
    endTime.value = undefined;
    TimeData.value = [];
    tableRef.value.refreshPaging();
    tableRef.value.loadData();
  };

  const del = async (id: number) => {
    await delPurchaseApplyList({ id });
    reset();
  };

  // 提交审核
  const Submit = async (data: any) => {
    data.state = 3;
    await PutPurchaseApplyList(data);
    reset();
  };

  const headerSave = async (val: any) => {
    try {
      const data = {
        userId: saveUserId.value.id,
        listType: 1,
        extend: JSON.stringify(val),
      };
      await PUTPurchaseHeader(data);
      headerSetting.list = [...val];
    } catch (err: unknown) {
      console.log(err);
    }
  };

  const SeeCauseDate = ref();
  const view = (content: string) => {
    SeeCauseDate.value = content;
    modelCauseVisible.value = true;
  };

  const searchState = (key: number) => {
    if (key === 1) {
      let into = JSON.parse(sessionStorage.getItem('loginInfo') as any);
      ownList.value = into.id;
      reset();
    } else {
      ownList.value = null;
      reset();
    }
  };

  const addBuyApply = () => {
    router.push({
      name: 'AddApplyPurchase',
    });
  };

  const edit = (id: number) => {
    router.push({
      name: 'editApplyPurchase',
      query: { id },
    });
  };

  // 在表格上显示的表头
  const selectedHeader = computed(() => {
    const arr: any = [];
    headerSetting.list.forEach((item: any) => {
      if (item.isDefault === 1) {
        arr.push(item);
      }
    });
    return arr;
  });

  const SeeDate = ref();

  const See = (item: any) => {
    modelVisible.value = true;
    SeeDate.value = item || [];
  };

  const search = () => {
    tableRef.value.refreshPaging();
    tableRef.value.loadData();
  };
</script>

<style scoped lang="less">
  // .content-head {
  // }
  .search-box {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    padding: 0px 10px;
  }

  :deep(.arco-space-item) {
    margin-top: 10px;
  }
  .Detail-item {
    cursor: pointer;
  }

  :deep(.arco-tabs-content) {
    padding-top: 0px;
  }

  .status {
    display: flex;
    align-items: center;
    justify-content: center;

    p {
      width: 12px;
      height: 12px;
      border-radius: 50%;
      margin-right: 10px;
    }
  }
</style>
